package com.example.qcrmdemo.Controller;

import com.example.qcrmdemo.entity.Role;
import com.example.qcrmdemo.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private RoleService roleService;
    @GetMapping("/login")
    public ModelAndView loginView(){
        ModelAndView mav=new ModelAndView("login");
        return mav;
    }
    @PostMapping("/login")
    public ModelAndView login(
            @RequestParam(name = "name",required = true,defaultValue = "")String name,
            @RequestParam(name = "password",required = true,defaultValue = "")String password,
            HttpSession session
    ){
        //创建一个Mav,假设正确登录，则重定向到主页
        ModelAndView mav=new ModelAndView("redirect:/index");
        //验证用户名密码是否存在，如果存在，则返回一个封装了用户登录信息的对象
       Role role=roleService.findByNamePass(name,password);
        if(role!=null){
            //如果登录用户存在，则登陆成功,然后，将该用户的信息保存在会话对象中，以便在整个操作中，都能访问登录信息
            session.setAttribute("role",role);
        }else {
            //如果没有找到该用户，则重定向一登录界面
            mav.setViewName("redirect:/login");
        }

        return mav;
    }
    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session, SessionStatus sessionStatus){
        ModelAndView mav=new ModelAndView("redirect:/login");
        //退出登录:核心是要清空会话对象
        session.removeAttribute("role");
        session.invalidate();
        //调用了Spring框架的会话状态的管理，结束会话状态
        sessionStatus.setComplete();
        return mav;
    }
}
